// pages/canvas/canvas.js
import util from '../../utils/savePhoto'

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    windowWidth: 0,
    windowHeight: 0,
    contentHeight: 0,
    thinkList: [],
    worryList: [],
    footer: '分享梦境，分享人生！',
    offset: 0,
    lineHeight: 30,
    title: "这是获取到的梦境标题",
    content: "这是获取到的梦境内容",
    keyword1: "关键词1",
    keyword2: "关键词2",
    keyword3: "关键词3",
    worry: "这是获取到的现实困扰内容",
    imgSrc: "../../static/images/default_bg.jpg"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          offset: (res.windowWidth - 300) / 2
        });
      }
    });
    this.setData({
      id: options.id
    })

    this.loadDreamDetail()
  },

  loadDreamDetail: function () {
    //获取梦境详情
    var that = this;
    var keys = "";
    //网络请求解析
    wx.request({
      url: 'https://api.jiemengshi.com/wechat/dream/record/get',
      data: {
        recordId: that.data.id,
      },
      header: {
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        console.log(res)
        console.log(res.data.data.record)
        var record = res.data.data.record

        keys = record.keyWord
        keys = that.decodeStr(keys)

        //设置数据显示
        that.setData({
          title: record.title,
          content: record.content,
          keyword1: keys[0],
          keyword2: keys[1],
          keyword3: keys[2],
          worry: record.worry
        })


        that.getData()
      },
      fail: function () {
        wx.showToast({
          title: '请求失败',
        })
      }
    })

  },

  //解析心情和关键词
  decodeStr: function (s) {
    s = s.substring(1, s.length - 1)
    s = s.split(",")
    return s
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  getData: function () {
    let that = this;

    let i = 0;
    let contentLineNum = 1;
    let thinkStr = '';
    let thinkList = [];
    for (let item of that.data.content) {
      if (item === '\n') {
        thinkList.push(thinkStr);
        thinkList.push('a');
        i = 0;
        thinkStr = '';
        contentLineNum += 1;
      } else if (i === 16) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        contentLineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }
    thinkList.push(thinkStr);

    let j = 0;
    let worryLineNum = 1;
    let worryStr = '';
    let worryList = [];
    for (let item of that.data.worry) {
      if (item === '\n') {
        worryList.push(worryStr);
        worryList.push('a');
        j = 0;
        worryStr = '';
        worryLineNum += 1;
      } else if (j === 16) {
        worryList.push(worryStr);
        j = 1;
        worryStr = item;
        worryLineNum += 1;
      } else {
        worryStr += item;
        j += 1;
      }
    }
    worryList.push(worryStr);

    that.setData({ thinkList: thinkList });
    that.setData( {worryList: worryList});
    that.createNewImg(contentLineNum, worryLineNum);
  },

  drawSquare: function (ctx, height) {
    ctx.rect(0, 0, this.data.windowWidth, height);
    ctx.setFillStyle("#f5f6fd");
    ctx.fill()
  },

  drawFont: function (ctx, content, height) {
    ctx.setFontSize(16);
    ctx.setFillStyle("#484a3d");
    ctx.setTextAlign('left');
    ctx.fillText(content, this.data.offset + 20, height);
  },

  drawTitle: function (ctx, content, height) {
    ctx.setFontSize(24);
    ctx.setFillStyle("#D2691E");
    ctx.setTextAlign('center')
    ctx.fillText(content, (this.data.windowWidth) / 2,height);
  },

  drawSubTitle: function (ctx, content, height) {
    ctx.setFontSize(20);
    ctx.setFillStyle("#D2691E");
    ctx.setTextAlign('left');
    ctx.fillText(content, this.data.offset, height);
  },

  drawFooter: function (ctx, content, height) {
    ctx.setFontSize(12);
    ctx.setFillStyle("#484a3d");
    ctx.setTextAlign('center')
    ctx.fillText(content, (this.data.windowWidth) / 2, height);
  },

  drawLine: function (ctx, height) {
    ctx.beginPath();
    ctx.setLineWidth(1);
    ctx.moveTo(this.data.offset, height);
    ctx.lineTo(this.data.windowWidth - this.data.offset, height);
    ctx.stroke('#eee');
    ctx.closePath();
  },

  createNewImg: function (contentLineNum, worryLineNum) {
    let that = this;
    let ctx = wx.createCanvasContext('myCanvas');

    let contentHeight = (contentLineNum + worryLineNum) * that.data.lineHeight + 570;
    that.setData({ contentHeight: contentHeight });

    that.drawSquare(ctx, contentHeight);

    let height = 10;
    ctx.drawImage(that.data.imgSrc, that.data.offset, height, that.data.windowWidth - that.data.offset * 2, 300);
    height += 340;
    that.drawTitle(ctx, that.data.title, height);
    
    height += 30;
    that.drawSubTitle(ctx,"梦境：",height);
    height += 30;

    for (let item of that.data.thinkList) {
      if (item !== 'a') {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }

    height += 20;
    that.drawSubTitle(ctx, "困扰：", height);
    height += 30;

    for (let item of that.data.worryList) {
      if (item !== 'a') {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }

    height += 20;

    // that.setData({ imageStartHeight: height });

    that.drawLine(ctx, (contentLineNum + worryLineNum) * that.data.lineHeight + 500);
    that.drawFooter(ctx, that.data.footer, (contentLineNum + worryLineNum) * that.data.lineHeight + 520);
    ctx.drawImage('../../static/images/jiemengshi.jpg', that.data.windowWidth - that.data.offset - 50, (contentLineNum + worryLineNum) * that.data.lineHeight + 510, 50, 50);
    ctx.draw();
  },

  changePic : function(){
    var that = this;
    var src = "";
    wx.chooseImage({
      // 设置最多可以选择的图片张数，默认9,如果我们设置了多张,那么接收时//就不在是单个变量了,
      count: 1,
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // 获取成功,将获取到的地址赋值给临时变量
        var tempFilePaths = res.tempFilePaths;
        src = tempFilePaths[0]
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
        that.setData({imgSrc: src});
        that.getData();
      }
    })
  },

  savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.data.windowWidth,
      height: that.data.contentHeight,
      canvasId: 'myCanvas',
      success: function (res) {
        util.savePicToAlbum(res.tempFilePath)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})